//
//  SearchGoods2.m
//  KYRR
//
//  Created by kuyuZJ on 2017/4/20.
//
//

#import "SearchGoods2.h"
#import "GoodsSearchCell.h"
#import "StoreListSearchCell.h"
#import "FruitInfo.h"
#import "Store2.h"

@interface SearchGoods2 ()<UISearchDisplayDelegate,UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UITableView* tableView;
@property(nonatomic,strong) NSMutableArray<MStore*>* arraySearch;
@property(nonatomic,strong) UISearchBar* searchBar;
@property(nonatomic,strong) NSString* keyword;
@property(nonatomic,strong) NetPage* pager;

@property(nonatomic,assign) BOOL isSearching;

@end

static NSString* const cellIdentifier =  @"cellIdentifier";

@implementation SearchGoods2

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layoutUI];
    [self layoutConstraints];
    [self refreshDataSource];
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(logoutNotification:) name:NotificationLogout object:nil];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.searchBar.translatesAutoresizingMaskIntoConstraints = false;
    self.searchBar.frame = CGRectMake(0, 0, SCREEN_WIDTH, 50);
    self.navigationItem.titleView = self.searchBar;
    //    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed: @"icon-search-store"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarTouch:)];
    [self.searchBar becomeFirstResponder];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.searchBar endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark =====================================================  试图布局
-(void)layoutUI{
    [self.view addSubview:self.tableView];
    
}
-(void)layoutConstraints{
    NSArray* formats = @[@"H:|-defEdge-[tableView]-defEdge-|", @"V:|-defEdge-[tableView]-defEdge-|"];
    NSDictionary* metrics = @{ @"defEdge":@(0)};
    NSDictionary* views = @{ @"tableView":self.tableView};
    for (NSString* format in formats) {
        NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:format options:0 metrics:metrics views:views];
        [self.view addConstraints:constraints];
    }
}

-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        weakSelf.pager.pageIndex ++;
        [weakSelf querySearch];
    }];
}

#pragma mark =====================================================  数据源
-(void)querySearch{
    NSDictionary* arg = @{@"ince":@"search_store",@"zoneid":self.Identity.location.circleID, @"shopcategory": @"3",@"keyword":self.keyword,@"page":[WMHelper integerConvertToString:self.pager.pageIndex]};
    
    NetRepositories* reposiories = [[NetRepositories alloc]init];
    [reposiories queryStore:arg page:self.pager complete:^(NSInteger react, NSArray *list, NSString *message) {
        if(self.pager.pageIndex == 1){
            [self.arraySearch removeAllObjects];
        }
        if(react == 1){
            [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [self.arraySearch addObject:obj];
            }];
        }else if(react == 400){
            [self alertHUD:message];
        }else{
            [self alertHUD:message];
        }
        [self.tableView reloadData];
        if(self.pager.pageCount<=self.pager.pageIndex){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        if(self.pager.pageIndex==1){
            [self.tableView.mj_header endRefreshing];
        }
        
    }];
}

#pragma mark =====================================================  <UITableViewDataSource>
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arraySearch.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    StoreListSearchCell* cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier forIndexPath:indexPath];
    [cell loadData:self.arraySearch[indexPath.row] keyword:self.keyword];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60.f;
}

#pragma mark =====================================================  <UITableViewDelegate>
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    MGoods* item =  self.arraySearch[indexPath.row];
//    FruitInfo* controller = [[FruitInfo alloc]initWithItem:item];
//    [self.navigationController pushViewController:controller animated:YES];
    Store2* controller = [[Store2 alloc]initWithItem:self.arraySearch[indexPath.row]];
    [self.navigationController pushViewController:controller animated:YES];
}


#pragma mark =====================================================  <UISearchBarDelegate>

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText   // called when text changes (including clear)
{
    [self.arraySearch removeAllObjects];
    self.keyword = searchText;
    self.pager.pageIndex = 1;
    [self querySearch];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar                     // called when cancel button pressed
{
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar;{
    [self.searchBar endEditing:YES];
}
#pragma mark =====================================================  SEL
-(IBAction)rightBarTouch:(id)sender{
    [self.searchBar becomeFirstResponder];
}

#pragma mark =====================================================  属性封装

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc]init];
        _tableView.delegate =self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[StoreListSearchCell class] forCellReuseIdentifier: cellIdentifier];
        _tableView.translatesAutoresizingMaskIntoConstraints = NO;
    }
    return _tableView;
}


-(UISearchBar *)searchBar{
    if(!_searchBar){
        _searchBar = [[UISearchBar alloc]init];
        _searchBar.delegate = self;
        _searchBar.placeholder =  @"请输入店铺、商品名称";
        _searchBar.tintColor = [UIColor lightGrayColor];
        //        _searchBar.showsCancelButton = YES;
    }
    return _searchBar;
}

-(NetPage *)pager{
    if(!_pager){
        _pager = [[NetPage alloc]init];
    }
    return _pager;
}

-(NSMutableArray *)arraySearch{
    if(!_arraySearch){
        _arraySearch = [[NSMutableArray alloc]init];
    }
    return _arraySearch;
}

@end
